#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/6 17:45
# @Author  : supuchun
# @Site    :
# @File    : get_message.py
import json
import logging
import multiprocessing

import pymysql
import requests
from model.mns_demo import ali_mns
from model.mysql_model import Mysql_zpt

obj_zpt = Mysql_zpt()
from model.simlog import Logger

failure_log = Logger('./log/failure_log.log', logging.WARNING, logging.DEBUG)
failure_date_log = Logger('./log/failure_date_log.log', logging.WARNING, logging.DEBUG)
date_log = Logger('./log/date_log.log', logging.WARNING, logging.DEBUG)


db = pymysql.connect(host="rm-2zezq40w18v8dqcy2.mysql.rds.aliyuncs.com", user="root", password="2bWP*qU8W$%",
                     database="zpt", charset="utf8", port=3306)
cursor = db.cursor()


def insert_png_tree(com_id, name):
	table_name = "png_tree"
	sql = """insert into {} SET com_id={},name='{}' """.format(table_name, com_id, name)
	print(sql)
	try:
		# 执行sql语句
		cursor.execute(sql)
		# 提交到数据库执行
		db.commit()
	except:
		# 如果发生错误则回滚
		failure_log.info(sql)
		db.rollback()


class get_surf:
	def __init__(self):
		self.send_queue = "elephant-wxp"
	
	def get_info(self):
		q = ali_mns(self.send_queue)
		rs_info = q.get_message(self.send_queue)
		date_log.info(rs_info)
		rs = json.loads(rs_info, encoding="utf-8")
		print rs
		try:
			id = rs["id"]
			name = rs["authour"]
			insert_png_tree(id, name)
		except:
			failure_date_log.info(rs_info)
			


if __name__ == '__main__':
	while True:
		a = get_surf()
		s = a.get_info()


# if __name__ == '__main__':
# 	pool = multiprocessing.Pool(processes=5)
# 	for i in range(6):
# 		pool.apply_async(run, )
#
# 	pool.close()
# 	pool.join()
#
